import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Col, Form, Input, message, Row, Select, Space, Table } from 'antd'
import { detailUserById, editUser } from '@/api/user'
import { useSearchParams } from 'react-router-dom'
import { useFormSupplier } from './useFormAdd'
import { EditFormVertical } from '@/components/CustomForm'
import { useForm } from 'antd/es/form/Form'
import { getRoleList } from '@/api/role'
import { useRoleColumns, useRoleColumnsDel } from './columns'
import useGetTableData from '@/hooks/useGetTableData'
import { applicationTypeEnum, AppListMap, AppListOptionsAndAll } from '@/constant'
import { ITableDataRoleList, ITableDataRoleListBack } from './types'
import './detail.less'
import { useAppSelector } from '@/store/hooks'
import { getOrgListDetail } from '@/api/org'
import { IOptionClass } from '@/pages/Goods/Plan'
import { getProductClassConfigByType } from '@/api/goods'
import PermissionButton from '@/components/PermissionButton'
const Index: React.FC = () => {
  const [FormSupplier] = useForm()
  const [FormRole] = useForm()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [desInfoList, setDesInfoList] = useState<IDesListType>([
    {
      label: '组织名称',
      key: 'orgName',
      content: '-',
    },
    { label: '用户工号', key: 'workId', content: '-' },
    { label: '用户姓名', key: 'name', content: '-' },
    { label: '手机号', key: 'phone', content: '-' },
  ])
  const [supplierOption, setSupplierOption] = useState<IOptionItem[]>([])
  const [isSupplierEdit, setisSupplierEdit] = useState<boolean>(false)
  const [isShowSelect, setisShowSelect] = useState<boolean>(true)
  const [isShowBigClass, setisShowBigClass] = useState<boolean>(true)
  const [selectedRowKeys, setselectedRowKeys] = useState<string[]>([])
  const [selectRowsInfo, setselectRowsInfo] = useState<ITableDataRoleList[]>([])
  const [classIdOptions, setclassIdOptions] = useState<IOptionClass[]>([])
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [query] = useSearchParams()
  const id = query.get('id')
  const grid = { xs: 24, sm: 24, md: 24, lg: 12, xl: 12, xxl: 12 }
  const { tableProps, search } = useGetTableData<ITableDataRoleList>(getRoleList, {
    form: FormRole,
    immediatelySend: false,
  })
  const [selectApp, setselectApp] = useState('')
  const [roleName, setRolename] = useState('')
  useEffect(() => {
    getDetail()
    getProductClassConfig()
  }, [])
  const getProductClassConfig = async (type = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 0 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
        }
      }) || []
    setclassIdOptions(classIdOptions)
  }
  const getDetail = async () => {
    const res = await detailUserById(id)
    if (res.code === 200) {
      setDetail(res.data)
      getSupList(res.data)
      search({ orgId: res.data.orgId })
      const data =
        desInfoList?.map((item) => {
          return {
            ...item,
            content: res.data[item.key] || '-',
          }
        }) || []
      setDesInfoList(data)
      FormSupplier.setFieldsValue({
        supplier: res?.data?.supplier || null,
        allSupplier: res?.data?.allSupplier,
        classAuthority: res?.data?.classAuthority || null,
        allClassAuthority: res?.data?.allClassAuthority,
      })
      if (res?.data?.allSupplier == 1) {
        setisShowSelect(false)
      }
      if (res?.data?.allClassAuthority == 1) {
        setisShowBigClass(false)
      }
      if (res.data.roleIds && res.data.roleIds.length > 0) {
        FormRole.setFieldsValue({
          roleIds: res.data.roleIds,
        })
      }
      if (res.data.userRoleList && res.data.userRoleList.length > 0) {
        const list =
          res?.data?.userRoleList?.map((it: ITableDataRoleListBack) => {
            return {
              id: it.roleId,
              roleName: it.roleName,
              applicationId: it.applicationId,
              applicationName: it.applicationName,
            }
          }) || []
        setselectRowsInfo(list)
        const keys =
          res?.data?.userRoleList.map(
            (rows: ITableDataRoleListBack) => `${rows?.roleId}--${rows?.roleName}--${rows?.applicationId}`,
          ) || []
        setselectedRowKeys(keys)
      }
    }
  }
  const startEditSupplier = () => {
    if (isSupplierEdit) {
      setispedding(true)
      FormSupplier.validateFields().then(async (data) => {
        const res = await editUser({
          id,
          ...detailInfo,
          allSupplier: isShowSelect ? 0 : 1,
          supplier: isShowSelect ? data.supplier : [],
          allClassAuthority: isShowBigClass ? 0 : 1,
          classAuthority: isShowBigClass ? (data.classAuthority ? data.classAuthority : null) : null,
        }).finally(() => setispedding(false))
        if (res.code === 200) {
          message.success('操作成功')
          setisSupplierEdit(false)
          getDetail()
        }
      })
    } else {
      setisSupplierEdit(true)
    }
  }

  const startEditRole = () => {
    FormRole.validateFields().then(async () => {
      setispedding(true)
      const res = await editUser({
        id,
        ...detailInfo,
        userRoleList: selectRowsInfo?.map((item) => {
          return {
            roleId: item.id,
            applicationId: item.applicationId,
          }
        }),
      }).finally(() => setispedding(false))
      if (res.code === 200) {
        message.success('操作成功')
        getDetail()
      }
    })
  }
  const getSupList = async (details: Record<string, any>) => {
    if (details.orgId) {
      const res = await getOrgListDetail<{ supplierPairs: { id: string; name: string }[] }>({ orgIds: [details.orgId] })
      if (res.code === 200) {
        const suppliers = res?.data[0]?.supplierPairs || []
        const supplierOption = suppliers?.map((item) => {
          return {
            label: item.name,
            value: item.id,
          }
        })
        setSupplierOption(supplierOption)
      }
    }
  }

  const onSelectChange = (val: any[]) => {
    const info = val.map((item) => {
      const arr = item?.split('--')
      return {
        id: arr[0],
        roleName: arr[1],
        applicationId: arr[2],
        applicationName: AppListMap[arr[2]],
      }
    })
    setselectedRowKeys(val)
    setselectRowsInfo(info)
  }
  const onDel = (info: ITableDataRoleList) => {
    const resetInfos = selectRowsInfo?.filter((it) => it.id != info.id)
    setselectRowsInfo([...resetInfos])
    const resetIds = selectedRowKeys?.filter((it) => it?.split('--')[0] != info.id)
    setselectedRowKeys([...resetIds])
  }
  return (
    <DetailContainer className="user_detail_page">
      <Descriptions title="基础信息" list={desInfoList}></Descriptions>
      <Descriptions
        title="数据权限"
        column={{ xxl: 2, xl: 2, lg: 2, md: 2, sm: 2, xs: 2 }}
        list={
          isSupplierEdit
            ? []
            : isRoot
            ? [
                {
                  label: '全部供应商权限',
                  key: '1',
                  content: detailInfo.allSupplier == 1 ? '是' : '否',
                },
                {
                  label: '供应商权限',
                  key: '2',
                  content:
                    detailInfo.allSupplier == 1
                      ? '全部'
                      : detailInfo.supplierInfoList?.reduce((acc: string, item: any, index: number) => {
                          return acc + (index === 0 ? '' : ',') + item.supplierName
                        }, '') || '-',
                },
                {
                  label: '全部大类权限',
                  key: '3',
                  content: detailInfo.allClassAuthority == 1 ? '是' : '否',
                },
                {
                  label: '大类权限',
                  key: '4',
                  content:
                    detailInfo.allClassAuthority == 1
                      ? '全部'
                      : detailInfo.classAuthorityList?.reduce((acc: string, item: any, index: number) => {
                          return acc + (index === 0 ? '' : ',') + item.className
                        }, '') || '-',
                },
              ]
            : [
                {
                  label: '供应商权限',
                  key: '2',
                  content:
                    detailInfo.allSupplier == 1
                      ? '全部'
                      : detailInfo.supplierInfoList?.reduce((acc: string, item: any, index: number) => {
                          return acc + (index === 0 ? '' : ',') + item.supplierName
                        }, '') || '-',
                },
                {
                  label: '全部大类权限',
                  key: '3',
                  content: detailInfo.allClassAuthority == 1 ? '是' : '否',
                },
                {
                  label: '大类权限',
                  key: '4',
                  content:
                    detailInfo.allClassAuthority == 1
                      ? '全部'
                      : detailInfo.classAuthorityList?.reduce((acc: string, item: any, index: number) => {
                          return acc + (index === 0 ? '' : ',') + item.className
                        }, '') || '-',
                },
              ]
        }
        extra={
          <Space>
            <PermissionButton permission="editData" type="primary" onClick={startEditSupplier} loading={ispedding}>
              {isSupplierEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {isSupplierEdit ? (
              <Button
                onClick={() => {
                  setisSupplierEdit(false)
                  getDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <div className="form_out_box">
          <EditFormVertical
            editConfig={useFormSupplier({
              supplierOption,
              isSupplierEdit,
              isShowSelect,
              setisShowSelect,
              isShowBigClass,
              setisShowBigClass,
              classIdOptions,
              isRoot,
            })}
            form={FormSupplier}
            initialValues={{ supplier: [], allSupplier: 0, classAuthority: [], allClassAuthority: 0 }}
          />
        </div>
      </Descriptions>
      <Descriptions
        title="角色权限"
        extra={
          <Space>
            <PermissionButton permission="editRole" type="primary" onClick={startEditRole} loading={ispedding}>
              保存
            </PermissionButton>
          </Space>
        }
      >
        <div className="rdaw_wrap">
          <div className="rdaw_header">
            <Form initialValues={{ select: '' }} style={{ width: 300 }} form={FormRole}>
              <Form.Item label="所属应用" name="select">
                <Select
                  options={AppListOptionsAndAll}
                  onChange={(val) => {
                    setselectApp(val)
                    search({ applicationId: val, roleName: roleName, orgId: detailInfo.orgId })
                  }}
                  placeholder="请选择所属应用进行搜索"
                ></Select>
              </Form.Item>
              <Form.Item label="角色名称" name="roleName">
                <Input
                  onChange={(event) => {
                    setRolename(event.target.value)
                    search({ applicationId: selectApp, roleName: event.target.value, orgId: detailInfo.orgId })
                  }}
                  placeholder="请输入角色名称进行搜索"
                ></Input>
              </Form.Item>
            </Form>
          </div>
          <Row className="role_detail_auth_wrap">
            <Col className="role_detailof_authbox" {...grid}>
              <div className="custom_table_style">
                <Table
                  bordered
                  columns={useRoleColumns()}
                  rowKey={(rows) => {
                    return `${rows?.id}--${rows?.roleName}--${rows?.applicationId}`
                  }}
                  scroll={{ y: 400 }}
                  rowSelection={{
                    selectedRowKeys,
                    preserveSelectedRowKeys: true,
                    onChange: onSelectChange,
                    getCheckboxProps: () => ({
                      disabled: !buttonCodeList.includes('editRole'),
                    }),
                  }}
                  rowHoverable={false}
                  rowClassName={(_, index) => {
                    return index % 2 === 0 ? '' : 'zebra-row-odd'
                  }}
                  {...tableProps}
                />
              </div>
            </Col>
            <Col className="role_detailof_selectinfos" {...grid}>
              <div className="rds_title">已选中角色</div>
              <div className="custom_table_style">
                <Table
                  bordered
                  columns={useRoleColumnsDel(onDel)}
                  dataSource={selectRowsInfo}
                  rowKey={(rows) => rows?.id}
                  scroll={{ y: 400 }}
                  pagination={false}
                  rowHoverable={false}
                  rowClassName={(_, index) => {
                    return index % 2 === 0 ? '' : 'zebra-row-odd'
                  }}
                />
              </div>
            </Col>
          </Row>
        </div>
      </Descriptions>
    </DetailContainer>
  )
}
export default Index
